using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MagnoliaTableAdapters;


public partial class Users : System.Web.UI.Page
{
    static int selectedIndex = -1;
        
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = ConfigurationManager.AppSettings["PageTitle"] + " - Data Tags";
        //GridView1.SelectedIndex = selectedIndex;
    }

    private bool LoadDataEmpty
    {
        //  some controls that are used within a GridView, such as the calendar control, can cuase post backs.
        //  we need to preserve LoadDataEmpty across post backs.
        get { return (bool)(ViewState["LoadDataEmpty"] ?? false); }
        set { ViewState["LoadDataEmpty"] = value; }
    }

    protected void GridView_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //  when binding a row, look for a zero row condition based on the flag.
        //  if we have zero data rows (but a dummy row), hide the grid view row
        //  and clear the controls off of that row so they don't cause binding errors
        if (LoadDataEmpty && e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Visible = false;
            e.Row.Controls.Clear();
        }
    }
    protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        ////  handle the save button on the footer row. this is the only manual data operation
        ////  that must be done. update and delete are handled by the gridview and ODS
        Lbl_EditorAlerts.Visible = false;

        selectedIndex = GridView1.SelectedIndex;

        if (e.CommandName == "Save")
        {
            string name = ((TextBox)GridView1.FooterRow.FindControl("TextBoxName")).Text;
            string address = ((TextBox)GridView1.FooterRow.FindControl("TextBoxAddress")).Text;
            string schema = ((TextBox)GridView1.FooterRow.FindControl("TextBoxSchema")).Text;
            string parser = ((TextBox)GridView1.FooterRow.FindControl("TextBoxParser")).Text;
            string defaultValue = ((TextBox)GridView1.FooterRow.FindControl("TextBoxDefaultValue")).Text;
            string lastValue = "Nothing";
            string lastSuccessfulRead = "1/01/1900 12:00:00 AM";
            string lastChecked = "1/01/1900 12:00:00 AM";

            bool pass = ValidateInput(-1, name);
            if (!pass)
                return;

            SqlDataSource1.InsertCommand = "sproc_WEB_InsertDataTag @Name ='" + name + "', @Address ='" + address + "', @Schema ='" + schema + "' ,@Parser='" + parser + "' ,@DefaultValue='" + defaultValue + "', @LastValue='" + lastValue + "' ,@Enabled='true' ,@HardCoded='false', @InUseNN='true' ,@LastSuccessfulRead='" + lastSuccessfulRead + "', @LastChecked='" + lastChecked + "', @PassThrough='true'";
            
            SqlDataSource1.Insert();
            GridView1.DataBind();
        }
        //else if (e.CommandName == "Update")
        //{
        //}
    }

    public bool ValidateInput(int tagID , string tagName)
    {
        bool pass = true;

        //string command = "Select ID from DataTag where Name='" + tagName + "'";

        //int ID = Convert.ToInt32(getDataObject(command));
                // query to get a list of items
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
        //SqlDataReader reader = null;
        try
        {
            conn.Open();

            String sProc = "sproc_WEB_DoesTagNameExist";

            SqlCommand cmd = new SqlCommand(sProc, conn);
            cmd.CommandType = CommandType.StoredProcedure;

            // set paramter
            DbParameter param = cmd.CreateParameter();
            param.ParameterName = "@Name";
            param.Value = Convert.ToString(tagName.Trim());
            param.DbType = DbType.String;
            cmd.Parameters.Add(param);

            DbDataReader reader = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(reader);
            reader.Close();

            int returnedID = Convert.ToInt32(dt.Rows[0].ItemArray[0]);

            if ( (returnedID != 0 && returnedID != tagID) 
                || (returnedID != 0 && Convert.ToInt32(dt.Rows[0].ItemArray[1]) != 21) )
            {
                pass = false;
                int returnedLevel = Convert.ToInt32(dt.Rows[0].ItemArray[1]);
                if (returnedLevel == 21)
                    Lbl_EditorAlerts.Text = "&#149; This tag name already exists as a data tag, please use a different tag name";
                else if (returnedLevel == 22)
                    Lbl_EditorAlerts.Text = "&#149; This tag name already exists as a string tag, please use a different tag name";
                else if (returnedLevel == 23)
                    Lbl_EditorAlerts.Text = "&#149; This tag name already exists as an image tag, please use a different tag name";
                Lbl_EditorAlerts.Visible = true;
            }
        }
        catch (Exception ex)
        {
            String err = ex.Message;
        }
        finally
        {
            conn.Close();
        }

        //if (ID != 0 && tagID != ID)
        //{
        //    pass = false;
        //    Lbl_EditorAlerts.Text = "* DateTag name is already existed, please use a different name";
        //}

        return pass;
    }

    //Connect to the database and retreve the return value
    public object getDataObject(string selectSQL)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataReader reader = null;
        object ob = 0;

        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            reader.Read();
            ob = reader[0];//Only read ONE data in the first of list
            reader.Close();

        }
        catch (Exception err)
        {
            //displayError("Error occur while connect to DataBase via DataReader, Check Connection : \n" + err);
        }
        finally
        {
            con.Close();
        }
        return ob;

    }
    protected void GridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        // cancel update if name is not unique
        int tagID = Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].FindControl("LabelID")).Text);
        String name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBoxName")).Text;

        bool pass = ValidateInput(tagID, name);
        if (!pass)
        {
            e.Cancel = true;
            return;
        }
    }
}
